/**
 * Project Name:lee
 * File Name:ActivitiController.java
 * Package Name:com.lee.activiti.controller
 * Date:2017年2月3日下午2:57:29
 * Copyright (c) 2017, chenzhou1025@126.com All Rights Reserved.
 *
 */
package com.lee.activiti.controller;

/**
 * ClassName:ActivitiController <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason:	 TODO ADD REASON. <br/>
 * Date:     2017年2月3日 下午2:57:29 <br/>
 * @author   dell
 * @version  
 * @since    JDK 1.6
 * @see 	 
 */
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.FormService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.lee.activiti.model.LeaveApply;
import com.lee.activiti.model.LeaveTask;
import com.lee.activiti.model.Process;
import com.lee.activiti.model.RunningProcess;
import com.lee.activiti.service.LeaveApplyService;
import com.lee.base.controller.BaseController;
import com.lee.common.page.PageView;

@Controller
@RequestMapping("/activiti/")
public class ActivitiController extends BaseController {
	@Resource
	ProcessEngine engine;
	@Autowired
	RepositoryService repservice;
	@Autowired
	RuntimeService runservice;
	@Autowired
	FormService formservice;
	@Autowired
	IdentityService identityservice;
	@Autowired
	TaskService taskservice;
	@Autowired
	HistoryService histiryservice;
	@Autowired
	LeaveApplyService leaveApplyService;

	@RequestMapping("intoActivitiIndex")
	public ModelAndView intoActivitiIndex(ModelAndView mav) {
		mav.setViewName("/activiti/index");
		return mav;
	}

	@RequestMapping("processlist")
	public ModelAndView processlist(ModelAndView mav) {
		mav.setViewName("/activiti/processlist");
		return mav;
	}

	/**
	 * 
	 * getprocesslists:(已部署的流程). <br/>
	 */
	@ResponseBody
	@RequestMapping("getprocesslists")
	public PageView getprocesslists(String pageNow, String pageSize) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map = toFormMap(pageNow, pageSize);
		int rowCount = pageView.getPageSize();
		int firstrow = pageView.getStartPage();
		List<ProcessDefinition> list = repservice.createProcessDefinitionQuery().listPage(firstrow, rowCount);
		int total = repservice.createProcessDefinitionQuery().list().size();
		List<Process> mylist = new ArrayList<Process>();
		for (int i = 0; i < list.size(); i++) {
			Process p = new Process();
			p.setDeploymentId(list.get(i).getDeploymentId());
			p.setId(list.get(i).getId());
			p.setKey(list.get(i).getKey());
			p.setName(list.get(i).getName());
			p.setResourceName(list.get(i).getResourceName());
			p.setDiagramresourcename(list.get(i).getDiagramResourceName());
			mylist.add(p);
		}
		pageView.setRecords(mylist);
		pageView.setRowCount(total);
		return pageView;
	}

	/**
	 * fileupload:(上传zip部署). <br/>
	 */
	@ResponseBody
	@RequestMapping("uploadworkflow")
	public String fileupload(@RequestParam MultipartFile uploadfile, HttpServletRequest request) {
		String flag = "false";
		try {
			MultipartFile file = uploadfile;
			String filename = file.getOriginalFilename();
			InputStream is = file.getInputStream();
			ZipInputStream zipInputStream = new ZipInputStream(is);
			repservice.createDeployment().name(filename).addZipInputStream(zipInputStream).deploy();
			flag = "true";
			// repservice.createDeployment().addInputStream(filename,
			// is).deploy();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * deletedeploy:(删除). <br/>
	 */
	@ResponseBody
	@RequestMapping("deletedeploy")
	public String deletedeploy(@RequestParam("deployid") String deployid) throws Exception {
		String flag = "false";
		try {
			// 级联删除,会删除和当前规则相关的所有信息，包括历史
			repservice.deleteDeployment(deployid, true);
			flag = "true";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * export:(显示流程图片). <br/>
	 */
	@ResponseBody
	@RequestMapping("showresource")
	public void export(@RequestParam("pdid") String pdid, @RequestParam("resource") String resource, HttpServletResponse response) throws Exception {
		ProcessDefinition def = repservice.createProcessDefinitionQuery().processDefinitionId(pdid).singleResult();
		InputStream is = repservice.getResourceAsStream(def.getDeploymentId(), resource);
		ServletOutputStream output = response.getOutputStream();
		IOUtils.copy(is, output);
	}

	// 启动流程定义
	@RequestMapping(value = "startleave", method = RequestMethod.POST)
	@ResponseBody
	public String start_leave(LeaveApply apply, HttpSession session) {
		int uid = (int)session.getAttribute("userSessionId");
		String userid = String.valueOf(uid);
		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("applyuserid", userid);
		ProcessInstance ins = leaveApplyService.startWorkflow(apply, userid, variables);
		System.out.println("流程id" + ins.getId() + "已启动");
		return JSON.toJSONString("sucess");
	}

	// 发起的流程
	@RequestMapping("setupprocess")
	@ResponseBody
	public PageView setupprocess(HttpSession session, String pageNow, String pageSize) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map = toFormMap(pageNow, pageSize);
		int rowCount = pageView.getPageSize();
		int firstrow = pageView.getStartPage();
		int uid = (int)session.getAttribute("userSessionId");
		String userid = String.valueOf(uid);
		List<ProcessInstance> a = runservice.createProcessInstanceQuery().processDefinitionKey("leave").involvedUser(userid).listPage(firstrow, rowCount);
		int total = (int) runservice.createProcessInstanceQuery().count();
		// int total=repservice.createProcessDefinitionQuery().list().size();
		List<RunningProcess> list = new ArrayList<RunningProcess>();
		for (ProcessInstance p : a) {
			RunningProcess process = new RunningProcess();
			process.setActivityid(p.getActivityId());
			process.setBusinesskey(p.getBusinessKey());
			process.setExecutionid(p.getId());
			process.setProcessInstanceid(p.getProcessInstanceId());
			LeaveApply l = leaveApplyService.findById(Integer.parseInt(p.getBusinessKey()));
			if (l.getUser_id().equals(userid)) {
				list.add(process);
			} else {
				continue;
			}
		}
		pageView.setRecords(list);
		pageView.setRowCount(total);
		return pageView;
	}

	// 查看流程进度
	@RequestMapping("traceprocess")
	@ResponseBody
	public void traceprocess(@RequestParam("executionid") String executionid, HttpServletResponse response) throws Exception {
		ProcessInstance process = runservice.createProcessInstanceQuery().processInstanceId(executionid).singleResult();
		BpmnModel bpmnmodel = repservice.getBpmnModel(process.getProcessDefinitionId());
		List<String> activeActivityIds = runservice.getActiveActivityIds(executionid);
		DefaultProcessDiagramGenerator gen = new DefaultProcessDiagramGenerator();
		// 获得历史活动记录实体（通过启动时间正序排序，不然有的线可以绘制不出来）
		List<HistoricActivityInstance> historicActivityInstances = histiryservice.createHistoricActivityInstanceQuery().executionId(executionid)
				.orderByHistoricActivityInstanceStartTime().asc().list();
		// 计算活动线
		List<String> highLightedFlows = leaveApplyService.getHighLightedFlows(
				(ProcessDefinitionEntity) ((RepositoryServiceImpl) repservice).getDeployedProcessDefinition(process.getProcessDefinitionId()),
				historicActivityInstances);

		InputStream in = gen.generateDiagram(bpmnmodel, "png", activeActivityIds, highLightedFlows, "宋体", "宋体", "宋体", null, 1.0);
		ServletOutputStream output = response.getOutputStream();
		IOUtils.copy(in, output);
	}

	// 领导审核(现在是查看自己的任务)
	@RequestMapping("depttasklist")
	@ResponseBody
	public PageView getdepttasklist(HttpSession session, String pageNow, String pageSize) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map = toFormMap(pageNow, pageSize);
		int rowCount = pageView.getPageSize();
		int firstrow = pageView.getStartPage();
		int userid = (int) session.getAttribute("userSessionId");
		String uid = String.valueOf(userid);

		List<LeaveApply> results = leaveApplyService.getpagedepttask(uid, firstrow, rowCount);
		int total = leaveApplyService.getalldepttask(userid);
		List<LeaveTask> tasks = new ArrayList<LeaveTask>();
		for (LeaveApply apply : results) {
			LeaveTask task = new LeaveTask();
			task.setApply_time(apply.getApply_time());
			task.setUser_id(apply.getUser_id());
			task.setEnd_time(apply.getEnd_time());
			task.setId(apply.getId());
			task.setLeave_type(apply.getLeave_type());
			task.setProcess_instance_id(apply.getProcess_instance_id());
			task.setProcessdefid(apply.getTask().getProcessDefinitionId());
			task.setReason(apply.getReason());
			task.setStart_time(apply.getStart_time());
			task.setTaskcreatetime(apply.getTask().getCreateTime());
			task.setTaskid(apply.getTask().getId());
			task.setTaskname(apply.getTask().getName());
			tasks.add(task);
		}
		pageView.setRecords(tasks);
		pageView.setRowCount(total);
		return pageView;
	}
	
	@RequestMapping(value="/dealtask")
	@ResponseBody
	public String taskdeal(@RequestParam("taskid") String taskid,HttpServletResponse response){
		Task task=taskservice.createTaskQuery().taskId(taskid).singleResult();
		ProcessInstance process=runservice.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
		LeaveApply leave=leaveApplyService.findById(new Integer(process.getBusinessKey()));
		return JSON.toJSONString(leave);
	}
	
	// 领导确认
	@RequestMapping(value = "deptcomplete")
	@ResponseBody
	public String deptcomplete(HttpSession session, @RequestParam("taskid") String taskid, HttpServletRequest req) {
		int uid = (int)session.getAttribute("userSessionId");
		String userid = String.valueOf(uid);
		Map<String, Object> variables = new HashMap<String, Object>();
		String approve = req.getParameter("deptleaderapprove");
		variables.put("deptleaderapprove", approve);
		taskservice.claim(taskid, userid);
		taskservice.complete(taskid, variables);
		return JSON.toJSONString("success");
	}

}
